import { localStorage, sessionStorage } from 'workplus-simple-storage';
import { SUCCESS_STATUS } from '@/constants/xhr-status';
import storageKeys from '@/constants/storage';
import PATHS from '@/constants/paths';
import defaultAvatar from '@/assets/atd-user-default.png';
import moment from 'moment';
import timeFormat from '@/constants/time-format';

const clone = obj => JSON.parse(JSON.stringify(obj));

const fixImagePath = (mediaId, defaultImage) => {
  if (typeof mediaId === 'undefined' || mediaId === 'undefined' || !mediaId) {
    return defaultImage || '';
  }
  return `${PATHS.BASE_URL}/images/${mediaId}`;
};

const fixAvatarPath = mediaId => fixImagePath(mediaId, defaultAvatar);

const replaceState = () => {
  window.history.replaceState(null, '', window.location.href.replace(window.location.search, ''));
};

const fetchSuccess = (res) => {
  if (res.status === SUCCESS_STATUS) {
    return true;
  }
  return false;
};

const getUserAttrByKey = (key) => {
  const userInfo = sessionStorage.get(storageKeys.user, true);
  if (userInfo[key]) {
    return userInfo[key];
  }
  return false;
};

const createOptions = (star, max, step, label) => {
  const options = [];
  for (let i = star; i < max + step; i += step) {
    options.push({
      value: i,
      label: `${i}${label}`,
      disabled: false,
    });
  }
  return options;
};

const fixScheduleTime = (name, sections) => {
  let time = `班次${name}: `;
  if (name === '') {
    time = '';
  }
  const nextDayDisplay = '次日';

  _.forEach(sections, (section) => {
    const isNextDayStart = section.start.across === 1;
    const isNextDayEnd = section.end.across === 1;

    if (isNextDayStart) {
      time += `${nextDayDisplay}${section.start.time}-`;
    } else {
      time += `${section.start.time}-`;
    }
    if (isNextDayEnd) {
      time += `${nextDayDisplay}${section.end.time} `;
    } else {
      time += `${section.end.time} `;
    }
  });
  return time;
};

const tagType = (index) => {
  const tagTypes = ['primary', 'success', 'warning', 'danger'];
  return tagTypes[index % tagTypes.length];
};

const downloadExcel = (downloadId, filename) => {
  const aElm = document.createElement('a');
  document.body.appendChild(aElm);
  aElm.href = `${PATHS.DOWNLOAD_URL}/download/excel/${downloadId}`;
  aElm.download = filename;

  setTimeout(() => {
    aElm.click();
    document.body.removeChild(aElm);
  }, 100);
};

const getTodayTime = () => {
  const yymmdd = moment(new Date()).format(timeFormat.ymd);
  const ymdhsm = `${yymmdd} 00:00:00`;
  return new Date(ymdhsm).getTime();
};

const getRootDepartment = () => {
  const { rootOrgId, orgId, domainId, all_employee_count } = sessionStorage.get(storageKeys.user, true);
  return {
    pathId: rootOrgId,
    orgId,
    domainId,
    allEmployeeCount: all_employee_count,
  };
};

const swapItems = (arr, index1, index2) => {
    // splice函数会立即修改原数组且返回被删除元素的数组，
　　arr[index1] = arr.splice(index2,1,arr[index1])[0]
　　return arr
};

export {
  clone,
  localStorage,
  sessionStorage,
  replaceState,
  fetchSuccess,
  getUserAttrByKey,
  createOptions,
  fixScheduleTime,
  tagType,
  fixImagePath,
  fixAvatarPath,
  downloadExcel,
  getTodayTime,
  getRootDepartment,
  swapItems
};
